package com.example.dayday.controller;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.server.HttpServerRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dayday.common.R;

import com.example.dayday.pojo.*;

import com.example.dayday.dto.TeacherDTO;
import com.example.dayday.service.CourseService;
import com.example.dayday.service.TeacherCourseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.dayday.service.TeacherService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.LockInfo;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Helen
 * @since 2022-09-07
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
public class TeacherController {


    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeacherCourseService teacherCourseService;

    @Autowired
    private CourseService courseService;


    @ApiOperation(value = "获取所有老师的姓名")
    @GetMapping("/getAllTeacherName")
    public R getAllTeacherName(){
        List<Teacher> teacher = teacherService.list();
        return R.ok().data("teacherList",teacher);
    }

    @ApiOperation(value = "获取这个课程未选的所有教师")
    @GetMapping("/getTeacherByCourseId")
    public R getTeacherByCourseId(String courseId,String teacherId,String teacherName){

        if (StringUtils.isEmpty(courseId)){
            return R.error("失败，请传入课程id");
        }

        LambdaQueryWrapper<TeacherCourse> teacherCourseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherCourseLambdaQueryWrapper.eq(TeacherCourse::getCourseId,courseId);
        List<TeacherCourse> teacherCourseList = teacherCourseService.list(teacherCourseLambdaQueryWrapper);//查出当前课程的选课老师id

        List<Long> teacherIds = teacherCourseList.stream().map(item -> {
            return item.getTeacherId();
        }).collect(Collectors.toList());

        System.out.println("已选老师"+teacherIds.toString());
        LambdaQueryWrapper<Teacher> teacherLambdaQueryWrapper = new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.notIn(teacherIds.size()>0,Teacher::getTeacherId,teacherIds);
        teacherLambdaQueryWrapper.like(StringUtils.isNotEmpty(teacherId),Teacher::getTeacherId,teacherId);
        teacherLambdaQueryWrapper.like(StringUtils.isNotEmpty(teacherName),Teacher::getTeacherName,teacherName);

        List<Teacher> teacher = teacherService.list(teacherLambdaQueryWrapper);
        return R.ok().data("teacherList",teacher);
    }




    @ApiOperation(value = "获取所有老师的信息")
    @GetMapping("/page")
    public R page(Integer current,Integer size,String teacherId,String teacherName){
        IPage<Teacher> page = new Page<>(current,size);//老师的信息
        IPage<TeacherDTO> it = new Page<>(current,size);//老师的分页信息

        LambdaQueryWrapper<Teacher> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotEmpty(teacherId), Teacher::getTeacherId,teacherId);
        qw.eq(StringUtils.isNotEmpty(teacherName), Teacher::getTeacherName,teacherName);


        List<Teacher> list = teacherService.page(page,qw).getRecords();

        BeanUtils.copyProperties(page,it);

        List<TeacherDTO> collect = list.stream().map((item) -> {
            LambdaQueryWrapper<TeacherCourse> qwt = new LambdaQueryWrapper<>();
            qwt.eq(TeacherCourse::getTeacherId, item.getTeacherId());

            List<TeacherCourse> tcList = teacherCourseService.list(qwt);

            TeacherDTO teacherDTO = new TeacherDTO();
            BeanUtils.copyProperties(item,teacherDTO);
            String courseName = "";
            for (int i = 0; i < tcList.size(); i++) {
                LambdaQueryWrapper<Course> qwc = new LambdaQueryWrapper<>();
                qwc.eq(Course::getCourseId, tcList.get(i).getCourseId());

                Course courses = courseService.getOne(qwc);
                if (i == tcList.size() - 1) {
                    courseName += "《" + courses.getCourseName() + "》";
                    break;
                }
                courseName += "《" + courses.getCourseName() + "》,";
            }
            teacherDTO.setCourseName(courseName);

            return teacherDTO;

        }).collect(Collectors.toList());

        it.setRecords(collect);

        return R.ok().data("teacherList",it);
    }
    @ApiOperation(value = "修改老师密码")
    @PostMapping("/updatePassword")
    public R updatePassword(String teacherId,String oldPassword, String newPassword, String twoPassword, HttpSession session){
        if(StringUtils.isEmpty(newPassword)){
            return R.error("新密码未输入");
        }
        if(StringUtils.isEmpty(twoPassword)){
            return R.error("确认密码未输入");
        }
        if(!newPassword.equals(twoPassword)){
            return R.error("两次密码不一致");
        }

        //是否是管理员来修改
        User user = (User) session.getAttribute("user");
        if(user.getRole()==2){
            Teacher teacher = (Teacher) user;
            String isAdmin = teacher.getIsAdmin();
            if("1".equals(isAdmin)){
                if(StringUtils.isEmpty(teacherId)){
                    return R.error("老师id未输入");
                }
                boolean b = teacherService.updatePassword(newPassword, Long.valueOf(teacherId));
                if (b){
                    return  R.ok().message("修改成功");
                }
                return R.error("该老师id不存在");
            }else{ //老师身份不是管理员
                //如果不是自己来修改
                if(!teacher.getTeacherId().equals(Long.valueOf(teacherId))){
                    return R.error("无权修改");
                }

                if(StringUtils.isEmpty(oldPassword)){
                    return R.error("旧密码未输入");
                }
                boolean b = teacherService.updatePassword(oldPassword, newPassword, teacher.getTeacherId());
                if (b){
                    return  R.ok().message("修改成功");
                }
                return R.error("修改失败,旧密码错误");
            }
        }else{
            return R.error("无权修改");
        }
    }

    @ApiOperation(value = "修改老师信息")
    @PutMapping("/updateTeacher")
    public R updateStudent(@RequestBody Teacher teacher,HttpSession session){
        //是否是管理员来修改
        User user = (User) session.getAttribute("user");
        if(user.getRole()==2){
            Teacher t = (Teacher) user;
            //是管理员或者是自己
            String isAdmin = t.getIsAdmin();
            if("1".equals(isAdmin)||t.getTeacherId().equals(teacher.getTeacherId())){
                boolean b = teacherService.updateById(teacher);
                if (b){
                    if(t.getTeacherId().equals(teacher.getTeacherId())){ //如果当前登录的是自己，session中的数据更新
                        teacher.setRole(2);
                        teacher.setUserId(teacher.getTeacherId());
                        session.setAttribute("user",teacher);
                    }
                    return R.ok().message("修改成功");
                }else{
                    return R.error("修改失败");
                }
            }else{
                //其他普通老师无权修改
                return R.error("无权修改");
            }
        }else{ //学生身份
             return R.error("无权修改");
        }
    }

    @ApiOperation(value = "根据id查询老师信息")
    @GetMapping("/getTeacher")
    public R getStudent(Long id){
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getTeacherId,id);
        Teacher teacher = teacherService.getOne(wrapper);
        teacher.setRole(2);
        return  R.ok().data("user",teacher);
    }

    @ApiOperation(value = "删除教师信息")
    @GetMapping("/delete")
    public R deleteTeacher(Long teacherId){
        teacherService.removeById(teacherId);
        return R.ok().message("删除成功！");
    }

    @ApiOperation(value = "添加新的老师信息")
    @PostMapping("/addTeacher")
    public R addStudent(@RequestBody Teacher t,HttpSession session){
        //要管理员才能添加
        User user = (User) session.getAttribute("user");
        if(user.getRole()==2){
            Teacher teacher = (Teacher) user;
            if("1".equals(teacher.getIsAdmin())){//如果是管理员
                t.setPassword("123456");
                //查询最大学号，最好写sql语句
                LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
                wrapper.orderByDesc(Teacher::getTeacherId).last("limit 1");
                Teacher one = teacherService.getOne(wrapper);

                Long teacherId = one.getTeacherId();//数据库最大学号  20190001

                LocalDateTime now = LocalDateTime.now();
                int year = now.getYear(); //今年 2022

                if(year * 10000-teacherId<0){ //表示最大的已经是超过今年，今年已经有学生
                    t.setTeacherId(one.getTeacherId()+1);
                }else{ //今年还没有学生
                    t.setTeacherId((long) (year * 10000  + 1));
                }
                teacherService.save(t);
                return R.ok().message("成功");
            }
        }
        return R.error("没有权限");

    }


    @ApiOperation(value = "导入教师信息")
    @PostMapping("/import")
    public void importTeacher(
            @RequestParam MultipartFile file,
            HttpServletResponse response,
            HttpServletRequest request
            ){
        try {
            InputStream stream = file.getInputStream();
            teacherService.importData(stream);
            response.sendRedirect(request.getContextPath()+"/dayday/chart.html?upload=true");
            //return R.ok().message("导入成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return R.error().message("导入失败！");
    }

}

